package logic

import (
	"context"
	"github.com/18767156402/x/errors"
	"github.com/golang-module/carbon"
	"shortUrl/internal/model"
	"shortUrl/internal/svc"
	"shortUrl/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type ShortenInfoLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewShortenInfoLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ShortenInfoLogic {
	return &ShortenInfoLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ShortenInfoLogic) ShortenInfo(req *types.ShortUrlInfoReq) (resp *types.ShortUrlInfoResp, err error) {
	var shortUrlModel model.ShortUrl
	var expireAtStr string
	var redirectCode int
	var id uint64
	shortenLogic := NewShortenLogic(l.ctx, l.svcCtx)
	longUrl := shortenLogic.getShortUrlFromCache(req.ShortenKey)
	redirectCode = shortenLogic.getRedirectCodeFromCache(req.ShortenKey)
	if longUrl == "" {
		result := l.svcCtx.Db.Model(&shortUrlModel).
			Where("shorten_key = ?", req.ShortenKey).Last(&shortUrlModel)
		if result.Error != nil {
			return nil, errors.New(1001, "获取短链详情失败")
		}
		longUrl = shortUrlModel.LongUrl
		redirectCode = shortUrlModel.RedirectCode
		id = shortUrlModel.ID
		if shortUrlModel.ExpireAt != nil {
			expireAtStr = carbon.FromStdTime(*shortUrlModel.ExpireAt).String()
		}
	}
	return &types.ShortUrlInfoResp{
		ID:           id,
		LongUrl:      longUrl,
		RedirectCode: redirectCode,
		ExpireAt:     expireAtStr,
	}, nil
}
